﻿// http://www.zimms.com
// Copyright (c) 2002-2007
// by James Zimmerman
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in the
// Software without restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
// Software, and to permit persons to whom the Software is furnished to do so, subject
// to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

using System;

/// <summary>
/// Represents an RFC 822 compliant email address. 
/// </summary>
/// Designed under the value object pattern (Evans, DDD).
[System.Serializable()]
public sealed class EmailAddress
{

    #region Fields

    private String _value;

    #endregion

    #region Constructor

    /// <summary>
    /// Initializes a new instance of the <see cref="EmailAddress"/> class.
    /// </summary>
    /// <param name="value">The email address.</param>
    /// <exception cref="System.FormatException"><paramref name="value"/> is not a properly formatted email address.</exception>
    public EmailAddress(String value)
    {
        this.Value = value;
    }

    #endregion

    #region Properties

    /// <summary>
    /// Gets or sets the value of the email address.
    /// </summary>
    /// <value>The value of the email address.</value>
    /// <exception cref="System.FormatException">The supplied value is not a properly formatted email address.</exception>
    public String Value
    {
        get
        {
            return this._value;
        }
        set
        {
            value = value == null ? String.Empty : value.Trim();
            if (!EmailAddress.IsEmail(value)) throw new FormatException(String.Format("\"{0}\" is not a properly formatted email address", value));

            this._value = value.ToLower();
        }
    }

    #endregion

    #region Behaviors

    /// <summary>
    /// Determines if the supplied value is a properly formatted email address.
    /// </summary>
    /// <param name="value"<The value to check.</param>
    /// <returns><see langkeyword="true">true</see> is it if properly formatted; otherwise <see langkeyword="false">false</see>.</returns>
    public static Boolean IsEmail(String value)
    {
        value = value == null ? System.String.Empty : value.Trim();
        return Regex.IsMatch(value, @"^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$");
    }

    #endregion

}

[TestFixture()]
public class EmailTests
{

    [Obsolete()]
    public EmailTests() { }

    [Test(Description = "Tests that the constructor doesnt allow nulls")]
    [ExpectedException(typeof(FormatException))]
    public void ConstructorDoesntAllowNull()
    {
        new EmailAddress(null);
    }

    [Test(Description = "Tests that the constructor doesnt allow empty strings")]
    [ExpectedException(typeof(FormatException))]
    public void ConstructorDoesntAllowEmpty()
    {
        new EmailAddress(" ");
    }

    [Test(Description = "Tests that the constructor doesnt allow incorrectly formed values")]
    [ExpectedException(typeof(FormatException))]
    public void ConstructorFormat()
    {
        new EmailAddress("asdfjdjf");
    }

    [Test(Description = "Tests the working constructor")]
    public void Constructor()
    {
        EmailAddress email = new EmailAddress("test@test.com");
        Assert.AreEqual("test@test.com", email.Value);
    }

    [Test(Description = "Tests that you can set the property")]
    public void ValueProperty()
    {
        EmailAddress email = new EmailAddress("test@test.com");
        email.Value = "test@test.net";
        Assert.AreEqual("test@test.net", email.Value);
    }

    [Test(Description = "Tests that the value property doesnt allow nulls")]
    [ExpectedException(typeof(FormatException))]
    public void ValuePropertyDoesntAllowNull()
    {
        EmailAddress email = new EmailAddress("test@test.com");
        email.Value = null;
    }

    [Test(Description = "Tests that the value property doesnt allow empty strings")]
    [ExpectedException(typeof(FormatException))]
    public void ValuePropertyDoesntAllowEmpty()
    {
        EmailAddress email = new EmailAddress("test@test.com");
        email.Value = " ";
    }

    [Test(Description = "Tests that the value property doesnt allow incorrect formats")]
    [ExpectedException(typeof(FormatException))]
    public void ValuePropertyFormat()
    {
        EmailAddress email = new EmailAddress("test@test.com");
        email.Value = "asadfasfg";
    }

    [Test(Description = "Tests that the IsEmail method correctly identifies formats")]
    public void IsEmail()
    {
        String[] emails = new String[] { null, " ", "asdf", "asdf@", "asdf@adsf", "asdf@asdf.", "@asdf.com", "asdf.com", ".com" };
        foreach (System.String email in emails)
        {
            Assert.IsFalse(EmailAddress.IsEmail(email));
        }
        Assert.IsTrue(EmailAddress.IsEmail("adsf@asdf.com"));
    }
}

